import fs from "fs";
import path from "path";
import getPkgToolsConfig, {
  getPackageJson,
} from "../utils/getPkgToolsConfig.js";
import { getBusinessProjectFilePath } from "../utils/index.js";

/**
 * 向dist 添加 package.json
 */
const generatePackageJson = async () => {
  const {
    outputDir,
    output = {},
    cjsDir,
    esDir,
    umdDir,
  } = await getPkgToolsConfig();
  const packageJson = getPackageJson();
  packageJson.script = undefined;
  packageJson.devDependencies = undefined;
  packageJson.publishConfig = undefined;
  packageJson.files = undefined;
  packageJson.resolutions = undefined;
  packageJson.packageManager = undefined;
  packageJson.main = `${cjsDir}/index.js`;
  packageJson.module = `${esDir}/index.js`;
  if (output.umd) {
    packageJson.unpkg = `${umdDir}/${output.name}.min.js`;
  }
  if (packageJson.typings) {
    packageJson.typings = path.join(cjsDir, path.basename(packageJson.typings));
  } else {
    packageJson.typings = path.join(
      cjsDir,
      path.basename(packageJson.main).replace(/\.js$/, ".d.ts")
    );
  }

  fs.writeFileSync(
    getBusinessProjectFilePath(`./${outputDir}/package.json`),
    JSON.stringify(packageJson, null, 2),
    {
      encoding: "utf8",
    }
  );
};
export default generatePackageJson;
